// 评论页面逻辑
const app = getApp();

Page({
  data: {
    shareId: null,
    share: {},
    comments: [],
    commentText: '',
    inputPlaceholder: '写评论...',
    inputFocus: false,
    sending: false,
    replyToCommentId: null,
    replyToUsername: ''
  },

  // 统一图片 URL 构造
  getImageUrl(path) {
    const { buildMediaUrl } = require('../../../utils/media');
    return buildMediaUrl(path);
  },

  onLoad(options) {
    // 兼容两种参数：?id= 或 ?shareId=
    const shareId = options.shareId || options.id;
    if (shareId) {
      this.setData({ shareId });
      this.loadShareDetail();
      this.loadComments();
    } else {
      wx.showToast({ title: '分享不存在', icon: 'none' });
      wx.navigateBack();
    }
  },

  // 加载分享详情
  async loadShareDetail() {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/social/get-share-detail`,
          method: 'GET',
          data: { share_id: this.data.shareId },
          header: {
            'Authorization': `Bearer ${app.globalData.token}`
          },
          success: resolve,
          fail: reject
        });
      });

      if (res.statusCode === 200 && res.data.success) {
        const share = res.data.data.share;
        // 格式化时间
        share.formatted_time = this.formatTime(share.created_at);
        this.setData({ share });
      } else {
        throw new Error(res.data.message || '加载失败');
      }
    } catch (error) {
      console.error('加载分享详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 加载评论列表
  async loadComments() {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/social/get-comments`,
          method: 'GET',
          data: {
            share_id: this.data.shareId
          },
          header: {
            'Authorization': `Bearer ${app.globalData.token}`
          },
          success: resolve,
          fail: reject
        });
      });

      if (res.statusCode === 200 && res.data.success) {
        const comments = res.data.data.map(comment => ({
          ...comment,
          formatted_time: this.formatTime(comment.created_at),
          replies: comment.replies ? comment.replies.map(reply => ({
            ...reply,
            formatted_time: this.formatTime(reply.created_at)
          })) : []
        }));
        this.setData({ comments });
      } else {
        throw new Error(res.data.message || '加载评论失败');
      }
    } catch (error) {
      console.error('加载评论失败:', error);
      wx.showToast({
        title: '加载评论失败',
        icon: 'none'
      });
    }
  },

  // 格式化时间
  formatTime(timeStr) {
    const now = new Date();
    const time = new Date(timeStr);
    const diff = Math.floor((now - time) / 1000);

    if (diff < 60) {
      return '刚刚';
    } else if (diff < 3600) {
      return `${Math.floor(diff / 60)}分钟前`;
    } else if (diff < 86400) {
      return `${Math.floor(diff / 3600)}小时前`;
    } else if (diff < 2592000) {
      return `${Math.floor(diff / 86400)}天前`;
    } else {
      return time.toLocaleDateString();
    }
  },

  // 预览图片
  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    const urls = e.currentTarget.dataset.urls;
    
    wx.previewImage({
      current: url,
      urls: urls
    });
  },

  // 评论输入
  onCommentInput(e) {
    this.setData({
      commentText: e.detail.value
    });
  },

  // 回复评论
  onReplyComment(e) {
    const commentId = e.currentTarget.dataset.id;
    const username = e.currentTarget.dataset.username;
    
    this.setData({
      replyToCommentId: commentId,
      replyToUsername: username,
      inputPlaceholder: `回复 @${username}：`,
      inputFocus: true
    });
  },

  // 发送评论
  async onSendComment() {
    if (!this.data.commentText.trim() || this.data.sending) {
      return;
    }

    // 检查登录状态
    if (!app.globalData.token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    this.setData({ sending: true });

    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/social/create-comment`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${app.globalData.token}`
          },
          data: {
            share_id: this.data.shareId,
            content: this.data.commentText.trim(),
            parent_id: this.data.replyToCommentId
          },
          success: resolve,
          fail: reject
        });
      });

      if (res.statusCode === 201 && res.data.success) {
        wx.showToast({
          title: '评论成功',
          icon: 'success'
        });
        
        // 清空输入框
        this.setData({
          commentText: '',
          replyToCommentId: null,
          replyToUsername: '',
          inputPlaceholder: '写评论...',
          inputFocus: false
        });
        
        // 重新加载评论
        this.loadComments();
      } else {
        throw new Error(res.data.message || '评论失败');
      }
    } catch (error) {
      console.error('发送评论失败:', error);
      wx.showToast({
        title: error.message || '评论失败',
        icon: 'none'
      });
    } finally {
      this.setData({ sending: false });
    }
  }
});
